package cc.chengheng.security.springmvc.service;

import cc.chengheng.security.springmvc.model.AuthenticationRequest;
import cc.chengheng.security.springmvc.model.UserDto;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class AuthenticationServiceImpl implements IAuthenticationService {

    // 用户信息
    private final Map<String,UserDto> userMap = new HashMap<>();
    {
        //region 分配权限
        Set<String> authorities1 = new HashSet<>();
        authorities1.add("p1");
        Set<String> authorities2 = new HashSet<>();
        authorities2.add("p2");
        //endregion

        userMap.put("zhangsan",new UserDto("1010","zhangsan","123","张三","133443"));
        userMap.put("lisi",new UserDto("1011","lisi","456","李四","144553"));
    }


    /**
     * 用户认证,验证用户是否合法
     * @param authenticationRequest
     * @return
     */
    @Override
    public UserDto authentication(AuthenticationRequest authenticationRequest) {
        // 校验参数是否为空
        if (authenticationRequest == null
                || StringUtils.isEmpty(authenticationRequest.getUsername())
                || StringUtils.isEmpty(authenticationRequest.getPassword())) {
                throw new RuntimeException("账号和密码为空");
        }

        // 模拟 从数据库查询出来的数据
        UserDto userDto = getUserDto(authenticationRequest.getUsername());

        // 查询出来的数据为空抛异常
        if (userDto == null) {
            throw new RuntimeException("账号和密码为空");
        }

        // 校验密码
        if (!authenticationRequest.getPassword().equals(userDto.getPassword())) {
            throw new RuntimeException("账号密码错误");
        }

        // 认证通过
        return userDto;
    }

    private UserDto getUserDto(String username) {
        return userMap.get(username);
    }
}
